const mongoose = require('mongoose')
const { MongoClient } = require('mongodb')

// 导入配置文件
const { DBHOST, DBPORT, DBNAME } = require('../config/config')

/**
 *
 * @param {Function} [success=() => console.log('数据库连接成功')] 数据库连接成功的回调
 * @param {Function} [error=err => console.error('数据库连接失败', err)] 数据库连接失败的回调
 */
module.exports = function (success = () => console.log('数据库连接成功'), error = (err) => console.error('数据库连接失败', err)) {
  // 连接字符串
  const CONNECTION_STRING = `mongodb://admin:123654@${DBHOST}:${DBPORT}/${DBNAME}?authSource=admin`

  // 连接 mongodb 服务
  mongoose.connect(CONNECTION_STRING)

  // 设置连接成功的回调
  mongoose.connection.once('open', () => {
    console.log('\x1b[32mMongoose connection open to MongoDB\x1b[0m')
    console.log(`\x1b[32mMongoDB Host:'${DBHOST}:${DBPORT}'\x1b[0m`)
    console.log(`\x1b[32mMongoDB Name:'${DBNAME}'\x1b[0m`)
    console.log(`\x1b[32mCurrent Node.js Version:'${process.version}'\x1b[0m`)
    const now = new Date()
    const formattedDate = `${now.getFullYear()}年${(now.getMonth() + 1).toString().padStart(2, '0')}月${now.getDate().toString().padStart(2, '0')}日${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`
    console.log(formattedDate, '🚀🚀🚀 服务已启动......')
    success()
  })

  // 设置连接错误的回调
  mongoose.connection.on('error', (err) => {
    console.error('Mongoose connection error:', err)
    error(err)
  })

  // 设置连接关闭的回调
  mongoose.connection.on('close', () => {
    console.log('Mongoose connection closed')
  })
}

// 使用 Promise 方式连接数据库
module.exports.connectWithPromise = function () {
  return new Promise((resolve, reject) => {
    module.exports(resolve, reject)
  })
}
